const router = require('koa-router')();
const getAccessToken = require('../../utils/getAccessToken')
var http = require('koa2-request');
const sha = require('sha1')
/**
 * 获取access_token填写client_credential
 * https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info
 * https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbeaeb1c48efb385c&secret=ea0822c57f63ca7766521b23492ec77c
 * 
 */

//微信验证
const serverWxToken = 'fzowk3bttij1wbdyah50rtsu50vg5itu'
router.get('/api/wxToken',async(ctx,next)=>{

    const {signature,echostr,timestamp,nonce} = ctx.request.query
    let str = [serverWxToken,timestamp,nonce].sort().join('')
    let sha1 = sha(str)
    // console.log(signature,console.log(signature,echostr,timestamp,nonce),timestamp,nonce)
    // console.log(signature,str)
    if(sha1 == signature){
        console.log('ppp')
        ctx.body = echostr
    }else{
        console.log('本次请求不是微信')
    }
})



const wxConfig = {
    appid:'wxbeaeb1c48efb385c',
    secret:'ea0822c57f63ca7766521b23492ec77c',
    token:'fzowk3bttij1wbdyah50rtsu50vg5itu'
}

const parseXml = (xml)=>{
    let {parseString} = xml2js;
    let res;
    parseString(xml,  {
        trim: true,
        explicitArray: false
    }, function (err, result) {
        res = result;
    });
    return res;
}

router.get('/cc',async(ctx,next)=>{
    let params =  await getAccessToken()
    const {body} = await http({
        method:'get',
        url:`https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=${params}`,
        // data:{access_token:await getAccessToken()}

    })
    // let obj = parseXml(body).xml;
    // console.log(res)
    // return
    console.log(JSON.parse(body))
    ctx.body = body
})



router.post('/post',async(ctx,next)=>{
    const {name} = ctx.request.body
    ctx.body = name
})
module.exports = router